package com.example.flowabledemo.config.auth;

import com.example.flowabledemo.data.entity.AaRole;
import com.example.flowabledemo.data.entity.AaUser;
import com.example.flowabledemo.data.pojo.SecUser;
import com.example.flowabledemo.service.DepartmentService;
import com.example.flowabledemo.service.UserService;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * @description 自定义账号密码角色验证
 */
@Component
public class CustomUserDetailsServiceImpl implements UserDetailsService {

  @Autowired
  private UserService userService;
  @Autowired
  private DepartmentService departmentService;


  @Override
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    if (StringUtils.isEmpty(username)) {
      throw new UsernameNotFoundException(null);
    }
    AaUser user = userService.getUser(username);
    if (user == null) {
      throw new UsernameNotFoundException("用户不存在");
    }

    List<AaRole> roles = userService.getRoles(username);
    List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
    roles.forEach(role -> {
      //security的验证规则需要ROLE_，由于我数据库是带上了ROLE_  所以不用加
      grantedAuthorities.add(new SimpleGrantedAuthority(role.getRoleName()));
    });
    SecUser secUser = new SecUser(username, new BCryptPasswordEncoder().encode(user.getPassword()), grantedAuthorities);
    secUser.setUsername(username);
    secUser.setName(user.getName());
    secUser.setJobName(user.getJobName());
    secUser.setDepartmentCode(user.getDepartmentCode());
    secUser.setDepartmentName(departmentService.get(user.getDepartmentCode()).getDepartmentName());
    return secUser;
  }
}
